import { useAPIUtils } from "@/components/APIUtilsProvider";
import ImageModal from "@/components/ImageModal";
import PageLayout from "@/components/PageLayout";
import ProductPill from "@/components/ProductPill";
import UserPill from "@/components/UserPill";
import {
  Blockquote,
  Box,
  Button,
  Flex,
  Grid,
  Group,
  Text,
  Textarea,
  Title,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { modals } from "@mantine/modals";
import dayjs from "dayjs";
import { Fragment } from "react";
import { useParams } from "react-router-dom";

export default function JoyMessageDetails() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const joyMessageQuery = tanstackQuery(`/api/joyMessages/${id}`);
  if (!joyMessageQuery.data) {
    return <></>;
  }
  const joyMessage = joyMessageQuery.data;

  return (
    <PageLayout title={"客户留言"}>
      <Grid w="96%">
        <Grid.Col span={4}>
          <Basics />
          <JoyMessageImages />
        </Grid.Col>

        <Grid.Col span={4} mt={"40"}>
          <Blockquote m={"lg"} icon="Q">
            {joyMessage.content}
          </Blockquote>
        </Grid.Col>
        <Grid.Col span={4} mt={40}>
          <Blockquote m={"lg"} icon="A">
            {joyMessage.reply}
          </Blockquote>
        </Grid.Col>
      </Grid>
    </PageLayout>
  );
}

const Descriptions = ({ title, data, tools }) => {
  return (
    <Box padding="md">
      {title && (
        <Flex justify={"space-between"} align={"baseline"}>
          <Title order={6} mb={"lg"}>
            {title}
          </Title>
          {tools}
        </Flex>
      )}
      <Grid gutter="0" style={{ border: "0.1px solid rgba(0, 0, 0, 0.1)" }}>
        {data.map((item, index) => (
          <Fragment key={index}>
            <Grid.Col
              span={2}
              bg={"gray.1"}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text weight={100} size="sm">
                {item.label}
              </Text>
            </Grid.Col>
            <Grid.Col
              span={item.block ? 10 : 4}
              p={12}
              style={{ border: "0.5px solid rgba(0, 0, 0, 0.1)" }}
            >
              <Text>{item.value}</Text>
            </Grid.Col>
          </Fragment>
        ))}
      </Grid>
    </Box>
  );
};

function Basics() {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const joyMessageQuery = tanstackQuery(`/api/joyMessages/${id}`);

  if (!joyMessageQuery.data) {
    return <></>;
  }

  const joyMessage = joyMessageQuery.data;

  const makeReply = async (id, values) => {
    await restPUT(`/api/admin/joyMessages/${joyMessage.channel}/${id}`, values);
    tanstackInvalidate(`/api/admin/joyMessages/${joyMessage.channel}`);
    tanstackInvalidate(`/api/joyMessages/${id}`);
  };

  const tools = (
    <Button.Group>
      <Button
        variant="default"
        disabled={joyMessage.replied}
        onClick={() =>
          openReplyModal({ data: joyMessage, onConfirm: makeReply })
        }
      >
        答复
      </Button>
    </Button.Group>
  );

  const descriptionsData = [
    {
      label: "分类",
      value: joyMessage.channel === "productConsult" ? "商品咨询" : "健康咨询",
    },
    {
      label: "状态",
      value: (
        <Text c={joyMessage.replied ? "green.6" : "red.6"}>
          {joyMessage.replied ? "已答复" : "待答复"}
        </Text>
      ),
    },
    {
      label: "提问人",
      value: <UserPill user={joyMessage.client} />,
    },
    {
      label: "提问时间",
      value: dayjs(joyMessage.createdAt).format("YYYY/MM/DD HH:mm:ss"),
    },
    {
      label: "答复人",
      value: <UserPill user={joyMessage.replyUser} />,
    },
    {
      label: "答复时间",
      value:
        joyMessage.replied &&
        dayjs(joyMessage.repliedAt).format("YYYY/MM/DD HH:mm:ss"),
    },
  ];

  if (joyMessage.channel === "productConsult" && joyMessage.subChannel) {
    descriptionsData.push({
      label: "商品",
      value: <ProductPill productId={joyMessage.subChannel} />,
      block: true,
    });
  }
  return (
    <>
      <Descriptions
        data={descriptionsData}
        title={`流水号: ${joyMessage.id}`}
        tools={tools}
      />
    </>
  );
}

function JoyMessageImages({ data }) {
  const { id } = useParams();
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const joyMessageQuery = tanstackQuery(`/api/joyMessages/${id}`);

  if (!joyMessageQuery.data) {
    return <></>;
  }

  const meta = joyMessageQuery.data?.meta;

  return (
    <>
      <Title order={6} mb={"lg"} mt="lg">
        提问人上传图片
      </Title>
      <Flex cols={3}>
        <ImageModal src={meta?.imageUrl0} />
        <ImageModal src={meta?.imageUrl1} />
        <ImageModal src={meta?.imageUrl2} />
        <ImageModal src={meta?.imageUrl3} />
        <ImageModal src={meta?.imageUrl4} />
        <ImageModal src={meta?.imageUrl5} />
      </Flex>
    </>
  );
}

function openReplyModal(props) {
  modals.open({
    title: "答复",
    size: "60%",
    centered: true,
    children: <ReplyForm onConfirm={props.onConfirm} data={props.data} />,
    labels: { confirm: "确定", cancel: "取消" },
  });
}

function ReplyForm({ onConfirm, data }) {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const form = useForm({
    initialValues: {
      reply: "",
    },

    validate: {},
  });

  return (
    <Box w="96%" mx="auto">
      <form
        onSubmit={form.onSubmit((values) => {
          onConfirm(data.id, values);
          modals.closeAll();
        })}
      >
        <Blockquote>{data.content}</Blockquote>

        <Textarea
          withAsterisk
          label="请填写答复"
          autosize
          maxRows={8}
          minRows={4}
          {...form.getInputProps("reply")}
        />

        <Group justify="flex-end" mt="md">
          <Button type="submit">Submit</Button>
        </Group>
      </form>
    </Box>
  );
}
